import pandas as pd
import hashlib
import numpy as np
import os
import json

def hash_dataframe(df, hash_algorithm=None, include_headers=None):
    # 加载配置文件
    if hash_algorithm is None or include_headers is None:
        config_path = os.path.join(os.path.dirname(__file__), "config.json")
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
            hashdata_config = config.get("hashdata", {})
            
            # 如果参数为None，则从配置文件中读取
            if hash_algorithm is None:
                hash_algorithm = hashdata_config.get("hash_algorithm", "sha256")
            if include_headers is None:
                include_headers = hashdata_config.get("include_headers", True)
        except Exception as e:
            print(f"无法加载配置文件，使用默认值: {e}")
            # 使用默认值
            if hash_algorithm is None:
                hash_algorithm = "sha256"
            if include_headers is None:
                include_headers = True
    """
    计算Pandas DataFrame数据的哈希值
    
    参数:
        df (DataFrame): Pandas DataFrame对象
        hash_algorithm (str): 哈希算法，如 'md5', 'sha1', 'sha256', 'sha512'
        include_headers (bool): 是否将列名包含在哈希计算中
        sort_data (bool): 是否在哈希计算前对数据进行排序
    
    返回:
        str: 数据的哈希值
    """
    if df is None or df.empty:
        raise ValueError("DataFrame为空或None")
    
    # 创建DataFrame的副本，避免修改原始数据
    df_copy = df.copy()
    
    # 处理NaN值，将其转换为空字符串
    df_copy = df_copy.fillna('')
    
    # 准备哈希计算的数据
    if include_headers:
        # 包含列名
        data_for_hash = []
        # 添加列名
        data_for_hash.append('|'.join(str(col) for col in df_copy.columns))
        # 添加数据行
        for _, row in df_copy.iterrows():
            data_for_hash.append('|'.join(str(cell) for cell in row))
        hash_input = '\n'.join(data_for_hash)
    else:
        # 仅数据内容
        hash_input = df_copy.to_csv(header=False, index=False, sep='|')
    
    # 计算哈希值
    hash_obj = hashlib.new(hash_algorithm)
    hash_obj.update(hash_input.encode('utf-8'))
    hash_value = hash_obj.hexdigest()
    
    return hash_value